package com.specter.mvc.web.spring;

import java.util.Objects;

import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.specter.mvc.model.Response;

import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class ConventionRequestValidateExceptionHandler {

    // 默认全局异常
    @Order(599)
    @ExceptionHandler(Exception.class)
    public Response defaultExceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return Response.failure(Objects.toString(e.getMessage(), "SYSTEM EXCEPTION !!!"));
    }

    // 数据绑定检验异常
    @Order(503)
    @ExceptionHandler(value = BindException.class)
    public Response bindExceptionHandler(BindException e) {
        String message = e.getMessage();
        if (!CollectionUtils.isEmpty(e.getBindingResult().getAllErrors())) {
            message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        }
        return Response.failure(message);
    }

    // 对象@Valid校验异常
    @Order(502)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response methodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getMessage();
        if (!CollectionUtils.isEmpty(e.getBindingResult().getAllErrors())) {
            message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        }
        return Response.failure(message);
    }

    // 格式约束校验异常
    @Order(501)
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Response constraintViolationException(ConstraintViolationException e) {
        String message = e.getMessage();
        if (e.getMessage() != null) {
            int index = e.getMessage().indexOf(":");
            message = index != -1 ? e.getMessage().substring(index + 1).trim() : e.getMessage();
        }
        return Response.failure(message);
    }
}